<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:5px;">
      <el-form :inline="true" :model="filterForm" :size="size">
        <el-form-item>
          <el-input v-model="filterForm.keyword" placeholder="请输入任务名称" :clearable="true"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="getData('search')">{{$t('action.search')}}</el-button>
          <!-- <kt-button icon="fa fa-search" :label="$t('action.search')" perms="sys:task:save" type="primary" @click="getData"/> -->
        </el-form-item>
        <el-form-item>
          <kt-button icon="fa fa-plus" :label="$t('action.add')" perms="sys:task:add" type="primary" @click="handleAdd"/>
        </el-form-item>
        <el-form-item>
          <kt-button icon="fa fa-trash-o" :label="$t('action.batchDelete')" perms="sys:task:batch" type="primary" @click="handleDeleteMore"/>
        </el-form-item>
      </el-form>
    </div>
	  <!--表格树内容栏-->
    <cs-table :table-data="tableData"
              :table-label="tableLabel"
              @handleButton="handleButton"
              :loading="loading"
              :selection="selectionType"
              @handleSortChange="handleSortChange"
              @handleSelectionChange="handleSelectionChange"
              :table-option="tableOption">
      <template slot="jobStatus" slot-scope="scope">
        <i class="el-icon-video-pause" style="font-size:20px; color:#7ebf50;cursor:pointer;" title="停止" v-if="scope.row.jobStatus ===0" @click="handleCellClick(scope.row)"></i>
        <i class="el-icon-video-play" style="font-size:20px; color:#e57471;cursor:pointer;" title="启动" v-if="scope.row.jobStatus ===1" type="danger" @click="handleCellClick(scope.row)"></i>
        <!-- <el-tag v-if="scope.row.jobStatus ===0" @click="handleCellClick(scope.row)"><i class="el-icon-video-pause"></i></el-tag>
        <el-tag v-if="scope.row.jobStatus ===1" type="danger" @click="handleCellClick(scope.row)"><i class="el-icon-video-play"></i></el-tag> -->
      </template>
      <template slot="bean" slot-scope="scope">
        <el-tag v-if="scope.row.bean" >是</el-tag>
        <el-tag v-if="!scope.row.bean" type="danger">否</el-tag>
      </template>
    </cs-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageRequest.pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageRequest.pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      style="text-align: right;"
      >
    </el-pagination>

    <el-dialog
      title="新增任务"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="600px"
			>
      <el-form
        :model="dataForm"
        :rules="dataFormRules"
        ref="dataForm"
        size="small"
        label-width="120px">
        <el-form-item
          label="任务名称"
          prop="jobName"
          maxlength="30">
          <el-input
            v-model="dataForm.jobName"
            placeholder="请输入任务名称"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="任务分组"
          prop="jobGroup">
          <el-input
            v-model="dataForm.jobGroup"
            :clearable="true"/>
        </el-form-item>
        <el-form-item
          label="调用方法"
          prop="classMethod">
          <el-input
            v-model="dataForm.classMethod"
            placeholder="请输入调用方法"
            :clearable="true"/>
        </el-form-item>

        <el-form-item
          label="cron表达式"
          prop="crontab">
          <el-input
            type="textarea"
            v-model="dataForm.crontab"
            placeholder=""
            :clearable="true"/>
            <div class="tips">
              <span><i class="el-icon-info"></i>如果是bean，请传入bean名+方法名,例：bean.method()</span>
              <span><i class="el-icon-info"></i>如果是普通类，请传入 类的全路径名+方法名：org.test.Bean.method()</span>
              <span><i class="el-icon-info"></i>目前参数类型仅支持封装类型，Integer、Boolean、Float、String</span>
            </div>
        </el-form-item>

        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item
              label="任务状态"
              prop="jobStatus">
              <el-radio v-model="dataForm.jobStatus" label="0">正常</el-radio>
              <el-radio v-model="dataForm.jobStatus" label="1">停止</el-radio>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item
              label="是否属于Bean"
              prop="bean">
              <el-switch
                v-model="dataForm.bean"
                active-value="0"
                inactive-value="1">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          size="small">取消</el-button>

        <el-button
          type="primary"
          :loading="dialogLoading"
          @click="submitForm"
          size="small">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      class="resultDialog"
      title="任务执行结果"
      :visible.sync="resultDialogVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="70%"
      style="height:95%"
			>
      <el-table
        border
        :data="resultData"
        max-height="600px"
        >
        <el-table-column
          prop="createTime"
          align="center"
          label="执行时间">
        </el-table-column>
        <el-table-column
          prop="result"
          align="center"
          label="执行结果">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.result === 1" >成功</el-tag>
            <el-tag v-if="scope.row.result === 0" type="danger">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="returnValue"
          align="center"
          label="返回值">
        </el-table-column>
      </el-table>

      <!-- <div slot="footer" class="dialog-footer">
        <el-button
          @click="resultDialogVisible = false"
          size="small">关闭</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton"
import { getTaskData, getResult, playTask, addTask, deleteTask, batchDeleteTask } from '@/api/task/timingtask'
export default {
  components:{
    KtButton,
    'CsTable': () => import('@/components/cs-table'),
	},
  data () {
    return {
      size: 'small',
      loading: false,
      selectionType: 'selection',
      tableLabel: [
        { label: '任务编号', param: 'id', align: 'center', minWidth: '8%', sortable: true, isShow: true },
        { label: '任务名称', param: 'jobName', align: 'center', minWidth: '10%', isShow: true, sortable: false },
        { label: '任务分组', param: 'jobGroup', align: 'center', minWidth: '10%', sortable: false, isShow: true },
        { label: '调用方法', param: 'classMethod', align: 'center', minWidth: '14%', sortable: false, isShow: true },
        { label: '执行表达式', param: 'crontab', align: 'center', minWidth: '10%', sortable: false, isShow: true },
        { label: '任务状态', param: 'jobStatus', align: 'center', minWidth: '8%', sortable: false, slot: true, isShow: true },
        { label: '创建时间',
          param: 'createTime',
          align: 'center',
          minWidth: '15%',
          sortable: true,
          render: (row) => {
            return row.createTime
          }
        },
        { label: '是否Bean', param: 'bean', align: 'center', minWidth: '10%', sortable: false, slot: true, isShow: true },
      ],
      tableOption: {
        label: '操作',
        width: '200',
        options: [
          { label: '查看结果', type: '', icon: '', methods: 'detail', auth: 'sys:task:detail' },
          { label: '删除', type: 'danger', icon: '', methods: 'delete', auth: 'sys:task:delete' }
        ]
			},
      tableData: [],
      totalPage: 0,
      multipleSelection: [],
      filterForm: {
        keyword: '',
        sort: '',
        field: ''
      },
      pageRequest: { pageNo: 1, pageSize: 10 },
      dialogVisible: false,
      dialogLoading: false,
      // 新增编辑界面数据
			dataForm: {
				id: '',
        jobName: '',
        jobGroup: '',
        classMethod: '',
				crontab: '',
        jobStatus: '0',
        createTime: '',
        bean: '0'
      },
      dataFormRules: {
				jobName: [
					{ required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 1, max: 30, message: '任务名称长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        jobGroup: [
					{ required: true, message: '请输入任务分组', trigger: 'blur' }
        ],
        classMethod: [
					{ required: true, message: '请输入方法名称', trigger: 'blur' }
        ],
        crontab: [
					{ required: true, message: '请输入cron表达式', trigger: 'blur' }
				]
      },
      resultDialogVisible: false,
      resultData: [],
      batchDeleteData: []
    }
  },
  created() {
    this.getData()
  },
  watch: {
    // 监控页面总数的变化，解决第二页的信息只有一条数据时，进行删除后，页面跳转至第一页，但没有将第一页的数据展示出来
    totalPage(){  // 注意这个函数的名字必须和你监听data中的属性的名字一样，这样才能当你data中的属性发生变化时，触发这个函数
      if(this.totalPage === ((this.pageRequest.pageNo - 1) * this.pageRequest.pageSize) && this.totalPage!=0){ // 这一行是关键代码，倍数关系
          this.pageRequest.pageNo -= 1
          this.findPage() // 获取表格数据的方法
      }
    }
  },
  methods: {
    getData(method) {
      if (method === 'search') {
        this.pageRequest.pageNo = 1
      }
      this.pageRequest.keyword = this.filterForm.keyword
      this.pageRequest.sort = this.filterForm.sort
      this.pageRequest.field = this.filterForm.field
      getTaskData(this.pageRequest).then(res => {
        if (res) {
          this.tableData = res.data.records
          this.totalPage = parseInt(res.data.total)
        }
      })
    },
    handleButton(methods, row, index) {
      // 修改
      if (methods.methods === 'detail') {
        this.handleDetail(methods.row)
      } else if (methods.methods === 'delete') { // 删除
        this.handleDelete(methods.row)
      }
    },
    // 排序
    handleSortChange(val) {
      this.filterForm.field = val.prop === 'id' ? val.prop : 'create_time'
      this.filterForm.sort = val.order === 'descending' ? 'desc' : 'asc'
      this.getData()

		},
    // 每页数
		sizeChangeHandle (val) {
			this.pageRequest.pageSize = val
      this.pageRequest.pageNo = 1
      this.getData()
		},
		// 当前页
		currentChangeHandle (val) {
      this.pageRequest.pageNo = val
      this.getData()
    },
    // 复选框选择事件
    handleSelectionChange(val) {
      this.batchDeleteData = val
    },
    // 新增
    handleAdd () {
      this.dialogVisible = true
      this.clearForm()
    },
    // 清空表单
    clearForm() {
      this.dataForm = {
        id: '',
        jobName: '',
        jobGroup: '',
        classMethod: '',
				crontab: '',
        jobStatus: '0',
        createTime: '',
        bean: '0'
      }
    },
    // 提交
    submitForm () {
      this.dataForm.jobStatus = 0
      this.dataForm.bean = this.dataForm.bean === '0' ? true : false
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          addTask(this.dataForm).then(res => {
            if (res.code === 200) {
              this.dialogVisible = false
              this.getData()
            } else {
              this.dataForm.bean = '0'
            }
          })
        } else {
          this.dataForm.bean = '0'
        }
      })

    },
    // 查看结果
    handleDetail (data) {
      getResult(data).then(res => {
        if (res.code === 200) {
          this.resultData = res.data
          this.resultDialogVisible = true
        }
      })
    },
    // 删除
    handleDelete (data) {
      let params = {
        id: data.id,
        jobName: data.jobName,
        jobGroup: data.jobGroup,
        classMethod: data.classMethod,
				crontab: data.crontab,
        jobStatus: data.jobStatus,
        bean: data.bean

      }
      this.$confirm('确认删除这条任务？', '提示', {}).then(() => {
				deleteTask(params).then(res => {
          if (res.code === 200) {
            this.getData()
          }
				})
			}).catch(() => {})
    },
    // 批量删除
    handleDeleteMore () {
      if (this.batchDeleteData.length > 0) {
        this.$confirm('确认批量删除这些任务？', '提示', {}).then(() => {
        	batchDeleteTask(this.batchDeleteData).then(res => {
            if (res.code === 200) {
              this.getData()
            }
        	})
        }).catch(() => {})
      } else {
        this.$message({
          message: '请选择要删除的数据',
          type: 'warning'
        })
      }

    },
    // 单元格点击--改变任务状态
    handleCellClick(row) {
      let params = {
        jobName: row.jobName,
        jobGroup: row.jobGroup,
        operation: row.jobStatus === 0 ? 'pause' : 'restart'
      }
      this.$confirm(`确定${row.jobStatus === 0 ? '停止' : '启动'}这条任务？`, '提示', {}).then(() => {
				playTask(params).then(res => {
          if (res.code === 200) {
            this.getData()
          }
        })
			})

    }
  }
}
</script>

<style lang="scss" scoped>
.tips{
  span{
    display: block;
    font-size: 12px;
    line-height: 25px;
    i{
      margin-right: 5px;
    }
  }
}
</style>
